package com.ssy.bus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssy.bus.mapper.CaseMapper;
import com.ssy.bus.mapper.DepartmentMapper;
import com.ssy.bus.mapper.OutpatientMapper;
import com.ssy.bus.mapper.PatientMapper;
import com.ssy.bus.pojo.Case;
import com.ssy.bus.pojo.Department;
import com.ssy.bus.pojo.Outpatient;
import com.ssy.bus.pojo.Patient;
import com.ssy.bus.service.ICaseService;
import com.ssy.bus.service.IOutpatientService;
import com.ssy.common.CodeMsg;
import com.ssy.common.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author ssy
 */
@Service
public class CaseServiceImpl extends ServiceImpl<CaseMapper, Case> implements ICaseService {

    @Autowired
    private CaseMapper caseMapper;

    @Autowired
    private IOutpatientService outpatientService;

    @Autowired
    private OutpatientMapper outpatientMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private PatientMapper patientMapper;

    @Override
    public Result insertCase(Case cases) {
        if (cases == null) {
            return new Result(CodeMsg.CASE_ERROR);
        }
        int i = this.caseMapper.insert(cases);
        return i > 0 ? new Result(cases.getId(), "病例保存成功") : new Result(CodeMsg.CASE_ERROR);
    }

    @Override
    public Result updateOutpatientState(String outpatientId) {
        Outpatient outpatient = new Outpatient();
        outpatient.setState(2);
        outpatientService.update(outpatient, new LambdaQueryWrapper<Outpatient>()
                .eq(Outpatient::getId, outpatientId));
        return new Result(CodeMsg.UPDATE_STATE_SUCCESS);
    }

    @Override
    public Result selectCaseByOutpatientId(String outpatientId) {
        Case caseOne = this.caseMapper.selectOne(new LambdaQueryWrapper<Case>()
                .eq(Case::getOutpatientId, outpatientId));
        Outpatient outpatient = outpatientMapper.selectById(outpatientId);
        if (caseOne == null || outpatient == null) {
            return new Result(CodeMsg.SELECT_OUTPATIENT_ERROR);
        }
        Department department = departmentMapper.selectById(outpatient.getDepId());
        caseOne.setDepName(department.getName());
        caseOne.setDoctorName(department.getResponsible());
        Patient patient = patientMapper.selectById(caseOne.getPantientId());
        caseOne.setPatientName(patient.getName());
        return new Result(caseOne);
    }
}
